package com.mrd.permissions;

import com.mrd.constant.SystemConstants;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.User;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

/**
 * <p> application name: sample <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author winaya
 */
//@Aspect
//@Component
public class PermissionIntercepter {
    /**
     * 必须为final String类型的,注解里要使用的变量只能是静态常量类型的，执行的action范围
     */
    public static final String EDP = "execution(* com.mrd.gtimp.*.action.*.*(..))";


    private static final Logger logger = Logger.getLogger(PermissionIntercepter.class);

    @Around(EDP)
    // spring中Around通知
    public Object logAround(ProceedingJoinPoint joinPoint) {
        String noLoginReturnString = "nologin";
        String roleFailReturnString = "rolefail";

        HttpServletRequest request = HttpUtils.getRequest();
        String t = request.getHeader("x-requested-with");
        // 判断是否为ajax请求
        if ("XMLHttpRequest".toLowerCase().equalsIgnoreCase(t)) {
            noLoginReturnString = "nologinAjax";
            roleFailReturnString = "rolefailAjax";
        }
        Object[] args = joinPoint.getArgs();
        Object obj = null;
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            Annotation noLogin = method.getDeclaringClass().getAnnotation(NoLogin.class);
            if (noLogin == null) {
                User user = (User) HttpUtils.getSession().getAttribute(SystemConstants.CURRENT_USER);
                // 判断用户是否登录
                if (user == null) {
                    logger.info("未登录或登录超时，进入登录页面!");
                    return noLoginReturnString;
                } else {
                    // 判断用户是否有执行该方法权限
                    Permissions pms = method.getAnnotation(Permissions.class);
                    if (pms != null) {
                        String permissionsId = pms.permissionsId();
                        List<com.mrd.gtimp.base.entity.Permissions> permissions = user
                                .getPermissions();
                        boolean havePer = false;
                        for (com.mrd.gtimp.base.entity.Permissions p2 : permissions) {
                            if (permissionsId.equals(p2.getPid())) {
                                havePer = true;
                                break;
                            }
                        }
                        if (!havePer) {
                            try {
                                StringBuffer logInfo = new StringBuffer();
                                logInfo.append("用户不具备此操作权限!").append("\n");
                                logInfo.append("权限id为:").append("\n");
                                logInfo.append(pms.permissionsId()).append("\n");
                                logInfo.append("用户信息为：").append("\n");
                                logInfo.append(user.toString()).append("\n");
                                logger.info(logInfo);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            HttpUtils.getRequest().setAttribute("msg", pms.msg());
                            return roleFailReturnString;
                        }
                    }
                }
            }
            obj = joinPoint.proceed(args);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return obj;
    }

}
